package sim

import (
	"context"
	"time"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/sagoo-cloud/sagooiot/internal/consts"
	"github.com/sagoo-cloud/sagooiot/internal/dao"
	"github.com/sagoo-cloud/sagooiot/internal/model"
	"github.com/sagoo-cloud/sagooiot/internal/service"
)

type sSimSimRealTraffic struct{}

func sSimSimRealTrafficNew() *sSimSimRealTraffic {
	return &sSimSimRealTraffic{}
}
func init() {
	service.RegisterSimSimRealTraffic(sSimSimRealTrafficNew())
}

// GetSimRealTrafficList 获取列表数据
func (s *sSimSimRealTraffic) GetSimRealTrafficList(ctx context.Context, in *model.GetSimRealTrafficListInput) (total, page int, list []*model.SimRealTrafficOutput, err error) {
	err = g.Try(ctx, func(ctx context.Context) {
		m := dao.SimRealTraffic.Ctx(ctx)
		if in.KeyWord != "" {
			m = m.Where(dao.SimRealTraffic.Columns().AccessNumber, in.KeyWord)
		}
		if in.Types != 0 {
			m = m.Where(dao.SimRealTraffic.Columns().Types, in.Types)
		}
		if in.MonthDay == 1 {
			m = m.Where(dao.SimRealTraffic.Columns().MonthDay, in.MonthDay).Where(dao.SimRealTraffic.Columns().RealDate, time.Now().Format("200601"))
		}
		if in.MonthDay == 2 {
			m = m.Where(dao.SimRealTraffic.Columns().MonthDay, in.MonthDay).Where(dao.SimRealTraffic.Columns().RealDate, time.Now().Format("20060102"))
		}
		total, err = m.Count()
		if err != nil {
			err = gerror.New("获取总行数失败")
			return
		}
		page = in.PageNum
		if in.PageSize == 0 {
			in.PageSize = consts.PageSize
		}
		err = m.Page(page, in.PageSize).Order("flow_amount desc").Scan(&list)
		if err != nil {
			err = gerror.New("获取数据失败")
		}
	})
	return
}

// GetSimRealTrafficById 获取指定ID数据
func (s *sSimSimRealTraffic) GetSimRealTrafficById(ctx context.Context, id int) (out *model.SimRealTrafficOutput, err error) {
	err = dao.SimRealTraffic.Ctx(ctx).Where(dao.SimRealTraffic.Columns().Id, id).Scan(&out)
	return
}

// AddSimRealTraffic 添加数据
func (s *sSimSimRealTraffic) AddSimRealTraffic(ctx context.Context, in model.SimRealTrafficAddInput) (err error) {
	db := dao.SimRealTraffic.Ctx(ctx).Where(dao.SimRealTraffic.Columns().AccessNumber, in.AccessNumber).
		Where(dao.SimRealTraffic.Columns().MonthDay, in.MonthDay)
	total, err := db.Count()
	if err != nil {
		return err
	}
	if total == 0 {
		_, err = db.Insert(in)
		return
	}
	if total > 0 {
		_, err = db.Update(in)
		return
	}
	return
}

// EditSimRealTraffic 修改数据
func (s *sSimSimRealTraffic) EditSimRealTraffic(ctx context.Context, in model.SimRealTrafficEditInput) (err error) {
	dao.SimRealTraffic.Ctx(ctx).FieldsEx(dao.SimRealTraffic.Columns().Id).Where(dao.SimRealTraffic.Columns().Id, in.Id).Update(in)
	return
}

// DeleteSimRealTraffic 删除数据
func (s *sSimSimRealTraffic) DeleteSimRealTraffic(ctx context.Context, Ids []int) (err error) {
	_, err = dao.SimRealTraffic.Ctx(ctx).Delete(dao.SimRealTraffic.Columns().Id+" in (?)", Ids)
	return
}
